//
//  AppDelegate.m
//  OrderSeat
//
//  Created by wangwei on 13-10-4.
//  Copyright (c) 2013年 wangwei. All rights reserved.
//

#import "AppDelegate.h"
#import "WelcomePageViewController.h"
#import "ShopHomeViewController.h"
#import "LoginViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "WXApi.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[AppDelegate sharedInstance] performSelector:@selector(startLocation)  withObject:nil afterDelay:3];
    
    [self initShareSDK];
    [[DbManager sharedManager] clearLikes];
    
    self.application = application;
    [self.application setStatusBarStyle:UIStatusBarStyleLightContent];
    
    self.tabBarController = [[TabBarController alloc] init];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = [self getRootViewController];
    [self.window makeKeyAndVisible];
    
    return YES;
}

- (void)startLocation
{
    _locationManager = [[LocationManager alloc] initWithDelegate:self];
    [_locationManager startUpdateLocation];
}

- (UIViewController *)getRootViewController
{
    if (![AppSetting isFirstLaunching]) {
        [AppSetting setFirstLaunching:YES];
        WelcomePageViewController *viewController = [[WelcomePageViewController alloc] init];
        return viewController;
    }
    else {
        return self.tabBarController;
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    self.location = newLocation;
    [AppSetting setLocation:newLocation];

    if (_locactionDelegate) {
        [_locactionDelegate locationManager:manager didUpdateToLocation:newLocation];
    }
    
    [[BaseDataManager sharedInstance] startDownLoad];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"UpdatedLocationNotification" object:nil];
}

- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    
    NSString *errorString;
    [manager stopUpdatingLocation];
    CLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"定位服务没有开启";
            //Do something...
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"定位的数据无效";
            //Do something else...
            break;
        default:
            errorString = @"定位出现了一个未知的错误";
            break;
    }
    [AppDelegate showMessage:errorString];
}

+ (void)shareWithTitle:(NSString *)title andContent:(NSString *)content andImage:(UIImage *)image
{
    //构造分享内容
    NSString *text = [NSString stringWithFormat:@"%@-%@",title,content];
    id<ISSContent> publishContent = [ShareSDK content:text
                                       defaultContent:@"美滋美位"
                                                image:[ShareSDK pngImageWithImage:image]
                                                title:text
                                                  url:@"http://www.mzmw.net"
                                          description:text
                                            mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions: nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]);
                                }
                            }];
}

+ (void)shareWithContent:(NSString *)content andImageURL:(NSString *)imageURL andLink:(NSString *)link
{
    //构造分享内容
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:@"美滋美位"
                                                image:[ShareSDK imageWithUrl:imageURL]
                                                title:content
                                                  url:link
                                          description:content
                                            mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil
                         shareList:nil
                           content:publishContent
                     statusBarTips:YES
                       authOptions:nil
                      shareOptions: nil
                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                                if (state == SSResponseStateSuccess)
                                {
                                    NSLog(@"分享成功");
                                }
                                else if (state == SSResponseStateFail)
                                {
                                    NSLog(@"分享失败,错误码:%d,错误描述:%@", [error errorCode], [error errorDescription]);
                                }
                            }];
}


- (void)initShareSDK
{
    [ShareSDK registerApp:@"13506987be10"];
    
    //添加新浪微博应用
    [ShareSDK connectSinaWeiboWithAppKey:@"3600650205"
                               appSecret:@"6ae1231f567835f993cc93c24e4951e3"
                             redirectUri:@"http://www.mzmw.net"];
    
    //添加腾讯微博应用
    [ShareSDK connectTencentWeiboWithAppKey:@"801438725"
                                  appSecret:@"65945f92675ee1b95f48373c467d92c6"
                                redirectUri:@"http://www.mzmw.net"];
    
    //添加QQ空间应用
    [ShareSDK connectQZoneWithAppKey:@"100549821"
                           appSecret:@"989f984e3d0994fcd799e9f2c578eeab"];
    
    //添加QQ应用
    [ShareSDK connectQQWithQZoneAppKey:@"100549821"                 //该参数填入申请的QQ AppId
                     qqApiInterfaceCls:[QQApiInterface class]
                       tencentOAuthCls:[TencentOAuth class]];
    
    //添加微信应用
    [ShareSDK connectWeChatWithAppId:@"wx62fe78509dc2075e"        //此参数为申请的微信AppID
                           wechatCls:[WXApi class]];
}

- (BOOL)application:(UIApplication *)application  handleOpenURL:(NSURL *)url
{
    return [ShareSDK handleOpenURL:url
                        wxDelegate:self];
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation
{
    return [ShareSDK handleOpenURL:url
                 sourceApplication:sourceApplication
                        annotation:annotation
                        wxDelegate:self];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

+ (AppDelegate*)sharedInstance
{
    return appDelegate;
}

+ (BOOL)checkLoginWithDelegate:(id)delegate
{
    if (![AppSetting isLogin]) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"系统提示" message:@"对不起，您还没有登录！" delegate:delegate cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    return YES;
}

+ (void)showMessage:(NSString *)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"系统提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

- (NSUInteger)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

+ (void)changeToNormalTabBar
{
    [AppDelegate sharedInstance].tabBarController.tab_delegate = nil;
    [[AppDelegate sharedInstance].tabBarController initButtons];
    [AppDelegate sharedInstance].tabBarController.tabbarView.hidden = NO;
}

+ (void)changeToShopTabBar:(ShopHomeViewController *)homeVC
{
    [[AppDelegate sharedInstance] showTabBar:homeVC.tabBarController];
    [AppDelegate sharedInstance].tabBarController.tab_delegate = homeVC;
    [[AppDelegate sharedInstance].tabBarController initButtons];
}

- (void)hideTabBar:(UITabBarController *) tabbarcontroller
{
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, ScreenHeight,
                                      view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
                                      view.frame.size.width, ScreenHeight)];
        }
    }
    self.tabBarController.tabbarView.hidden = YES;
}

- (void)showTabBar:(UITabBarController *) tabbarcontroller
{
    for(UIView *view in tabbarcontroller.view.subviews)
    {
        if([view isKindOfClass:[UITabBar class]])
        {
            [view setFrame:CGRectMake(view.frame.origin.x, ScreenHeight-49,
                                      view.frame.size.width, view.frame.size.height)];
        }
        else
        {
            [view setFrame:CGRectMake(view.frame.origin.x, view.frame.origin.y,
                                      view.frame.size.width, ScreenHeight-49)];
        }
    }
    self.tabBarController.tabbarView.hidden = NO;
}

@end









